package icu.groot.alan.servlet.report;

import com.alibaba.excel.EasyExcel;
import icu.groot.alan.entity.ReportExport;
import icu.groot.alan.service.ReportService;
import icu.groot.alan.service.impl.ReportServiceImpl;
import icu.groot.alan.util.MergeStrategy;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

@WebServlet("/report/export/excel.export")
public class ReportExportExcelServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("健康上报", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        Map<String, List<ReportExport>> reportExcelMap = new ReportServiceImpl().reportExcel(Integer.parseInt(req.getParameter("id")));
        Set<Map.Entry<String, List<ReportExport>>> entries = reportExcelMap.entrySet();
        List<ReportExport> reportExports = new ArrayList<>();
        List<String> departments = new ArrayList<>();
        ReportExport head = new ReportExport("工号", "姓名", "异常情况");
        for (Map.Entry<String, List<ReportExport>> entry : entries) {
            departments.add(entry.getKey());
            reportExports.add(new ReportExport(entry.getKey()));
            reportExports.add(head);
            reportExports.addAll(entry.getValue());
        }
        // 这里需要设置不关闭流

        EasyExcel.write("test.xlsx", ReportExport.class)
                //不需要表头
                .needHead(false)
                .registerWriteHandler(new MergeStrategy(departments))
                .sheet("通用合并行策略")
                .doWrite(reportExports);
        EasyExcel.write(response.getOutputStream(), ReportExport.class)
                //不需要表头
                .needHead(false)
                .registerWriteHandler(new MergeStrategy(departments))
                .autoCloseStream(Boolean.FALSE).sheet("健康上报")
                .doWrite(reportExports);
    }
}
